package app.filter;

import cn.hutool.core.util.URLUtil;
import com.dj.gateway.app.authorization.dto.DJUserInfo;
import com.dj.gateway.app.authorization.dto.MemberInfo;
import com.dj.gateway.app.context.OAuth2AuthenticationContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.util.function.Consumer;

public class UserInfoTransferFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        OAuth2Authentication authenticationInfo = OAuth2AuthenticationContextHolder.getUserAuthentication();
        if (authenticationInfo != null && authenticationInfo.getUserAuthentication() != null
                && authenticationInfo.getUserAuthentication().getPrincipal() != null) {
            DJUserInfo djUserInfo = (DJUserInfo) authenticationInfo.getUserAuthentication().getPrincipal();
            MemberInfo memberInfo = (MemberInfo) djUserInfo.getUserData();

            Consumer<HttpHeaders> httpHeaders = httpHeader -> {
                httpHeader.set("uid", String.valueOf(memberInfo.getId()));
                httpHeader.set("uname", URLUtil.encode(StringUtils.trimToEmpty(memberInfo.getNickname()), Charset.forName("UTF-8")));
                httpHeader.set("phone", String.valueOf(memberInfo.getMob()));
            };
            ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().headers(httpHeaders)
                    .build();
            exchange.mutate().request(serverHttpRequest).build();
        }

        OAuth2AuthenticationContextHolder.cleanUserAnthentication();

        return chain.filter(exchange);
    }
}
